//
//  WWRegisterViewController.m
//  WeiWeiHaircut
//
//  Created by 超群 on 15/10/8.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "WWRegisterViewController.h"
#import "WWRegisterCell.h"
#import "MLInputDodger.h"
#import "UIButton+timer.h"
#import "UserAgreementViewController.h"
@interface WWRegisterViewController () <UITableViewDelegate,UITableViewDataSource,QZRequestProtocol>
@property (strong,nonatomic)QZRequest *request;
@property (weak, nonatomic) IBOutlet UIButton *agreeButton;
@property (weak, nonatomic) IBOutlet UILabel *agreeLabel;

@end

@implementation WWRegisterViewController{
    NSString *_phoneNumber;//电话号码
    UIButton *_codeButton;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleWithSting:@"注册"];
    [self buildTableViewUI];
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidenKeyBoard)];
    [self.view addGestureRecognizer:tap];
    
    QZRequest *request = [[QZRequest alloc]init];
    request.delegate = self;
    self.request = request;
    UITapGestureRecognizer *tapAgg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(agreeLabelClick)];
    self.agreeLabel.userInteractionEnabled = YES;
    [self.agreeLabel addGestureRecognizer:tapAgg];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //距离键盘距离(躲避键盘)
    self.tableView.shiftHeightAsDodgeViewForMLInputDodger = 50;
    //注册
    [self.tableView registerAsDodgeViewForMLInputDodger];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)buildTableViewUI
{
    self.tableView.delegate         = self;
    self.tableView.dataSource       = self;
    self.tableView.backgroundColor  = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([WWRegisterCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([WWRegisterCell class])];
}

- (void)hidenKeyBoard
{
    [self.view endEditing:YES];
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

#pragma mark - tableView datasource
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WWRegisterCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WWRegisterCell class]) forIndexPath:indexPath];
    [cell.textField setTag:indexPath.row+1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.getCodeButton.hidden = NO;
        cell.titleLabel.text = @"手机号";
        cell.textField.keyboardType = UIKeyboardTypeNumberPad;
        
        [cell.getCodeButton addTarget:self action:@selector(getCodeAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    if (indexPath.row == 1) {
        cell.titleLabel.text = @"验证码";
        cell.textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    if (indexPath.row == 2) {
        cell.titleLabel.text = @"密码";
        cell.textField.secureTextEntry = YES;
    }
    if (indexPath.row == 3) {
        cell.textField.secureTextEntry = YES;
    }
    
    return cell;
}
#pragma mark- 获取验证码
-(void)getCodeAction:(UIButton *)btn
{
    UITextField* textfield = (UITextField*)[self.view viewWithTag:1];
    _phoneNumber = textfield.text;
    _codeButton = btn;
    if(![self checkTextfieldText:textfield]){
        [[iToast makeText:@"手机号不能为空"] show];
        return;
    }
    if (![self isValidateMobile:[textfield.text delSpace]]) {
        [[iToast makeText:@"请输入正确的手机号"] show];
        return;
    }
    //先判断验证手机号是否注册，再发验证码
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",newPublicURL,@"User.GetTelJc"];
    
    NSDictionary *dic = @{
                          @"username":textfield.text,
                          @"user_type":@(1)
                          };
    [self.request QZRequest_POST:urlStr parameters:dic tagNSString:@"User.GetTelJc" stopRequest:NO isSerializer:NO isCache:NO];
}
- (void)backLoginTap
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark- 注册按钮
- (IBAction)submitTap:(UIButton* )sender {
    if (!_agreeButton.selected) {
        [[iToast makeText:@"请同意条款"] show];
        return;
    }
    
    UITextField* textfield1 = (UITextField*)[self.view viewWithTag:1];
    UITextField* textfield2 = (UITextField*)[self.view viewWithTag:2];
    UITextField* textfield3 = (UITextField*)[self.view viewWithTag:3];
    UITextField* textfield4 = (UITextField*)[self.view viewWithTag:4];
    NSString* firstrPassword = [textfield3.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* secondPassword = [textfield4.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (![self checkTextfieldText:textfield1]) {
        [[iToast makeText:@"手机号不能为空"] show];
    }
    if (![self checkTextfieldText:textfield2]) {
        [[iToast makeText:@"验证码不能为空"] show];
    }
    if (![self checkTextfieldText:textfield3]) {
        [[iToast makeText:@"密码不能为空"] show];
    }
    if (![self checkTextfieldText:textfield4]) {
        [[iToast makeText:@"请再次输入密码"] show];
    }
    if (![firstrPassword isEqualToString:secondPassword]) {
        [[iToast makeText:@"两次输入密码不一致"] show];
    }else{
        
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",newPublicURL,@"User.GetRegister"];
        NSDictionary *dic = @{@"username":[textfield1.text delSpace],//用户名
                              @"code" :[textfield2.text delSpace],//验证码
                              @"password" :[textfield3.text delSpace],//密码
                              @"password2" :[textfield4.text delSpace],//密码2
                              @"user_type" :@(1)};//用户类型
        [self.request QZRequest_POST:urlStr parameters:dic tagNSString:@"User.GetRegister" stopRequest:NO isSerializer:NO isCache:NO];
    }
}
#pragma  mark QZRequestProtocol
-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag
{
  
    [[iToast makeText:value[@"info"]] show];
    if ([tag isEqualToString:@"User.GetRegister"]) {//注册
       NSString *info = value[@"data"][@"info"];
        
        if ([value[@"data"][@"status"] intValue] == 100) {
            [[iToast makeText:@"注册成功!"] show];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [[iToast makeText:info] show];
        }
        
    }else if ([tag isEqualToString:@"User.GetSmsCode"]){//获取验证码
        
        if ([value[@"data"][@"status"] integerValue]  ==100) {
            [[iToast makeText:@"验证码已发送"] show];
        }else{
            [[iToast makeText:@"验证码已失败"] show];
        }

    }
    
    if ([tag isEqualToString:@"User.GetTelJc"]) {// 判断手机是否注册
        if ([value[@"data"][@"status"] integerValue] == 100) {//已注册
            [[iToast makeText:@"改用户已注册"] show];
        }else{//未注册
                NSString *urlStr = [NSString stringWithFormat:@"%@%@",newPublicURL,@"User.GetSmsCode"];
                NSDictionary *dic = @{@"tel":[_phoneNumber delSpace]};
                [self.request QZRequest_POST:urlStr parameters:dic tagNSString:@"User.GetSmsCode" stopRequest:NO isSerializer:NO isCache:NO];
                [_codeButton addTimer];
        }
        
    }
}
/*手机号码验证*/
-(BOOL) isValidateMobile:(NSString *)mobile
{
    NSString *phoneRegex = @"^1[3|4|5|7|8]\\d{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
- (BOOL )checkTextfieldText:(UITextField*)textField
{
    NSString* firstrPassword = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([firstrPassword isEqualToString:@""]) {
        return NO;
    }else
        return YES;
}
#pragma mark- 同意条款
- (IBAction)agreeDelegateTap:(UIButton* )sender {
    
    sender.selected = !sender.selected;

}
-(void)agreeLabelClick{
    
    UserAgreementViewController *vc= [[UserAgreementViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

@end
